<script setup>
import { ref, onMounted } from 'vue'
import easyapi from '../api'
import { ElMessage, ElMessageBox, pageHeaderEmits } from 'element-plus'
//定义绑定的数据
const tableData = ref([]);
//控制新增信息窗口是否显示
const addWinVisible = ref(false);
//新增数据绑定对象
const addObject = ref({});
//控制新增信息窗口是否显示
const editWinVisible = ref(false);
//编辑数据绑定对象
const editObject = ref({});
//记录编辑数据的下标
var editIndex = -1;
//分页的总页数
const total = ref(100)
//查询数据输入框的绑定对象
const checkObj = ref({
    size: 3,
    page: 1
})

//类型
const types = ref([])
//状态
const status = ref([])



onMounted(async function () {
    checkData();
})

//删除数据
const del = function (index, row) {
    ElMessageBox.confirm(
        '确认删除该行数据吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //提交数据
            let result = await easyapi.del('/api/trainer', row.trainerID)
            if (result.code == 200) {
                //刷新表单数据
                tableData.value.splice(index, 1)
                if (tableData.value.length == 0) {
                    checkObj.value.page = (checkObj.value.page - 1) < 1 ? 1 : checkObj.value.page - 1;
                    checkData(checkObj.value.page)
                } else {
                    checkData(checkObj.value.page)
                }
                //提示删除成功
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            } else {
                ElMessage({
                    type: 'error',
                    message: result.message,
                })
            }

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

//新增数据
//显示新增窗口
const openAddWin = async function () {
    addObject.value = {}
    imageUrl.value = 'api' + '/img/default.png'
    addWinVisible.value = true;
}
//关闭新增窗口
const closeAddWin = function () {
    addWinVisible.value = false;
}

const imageUrl = ref({})

const handleAvatarSuccess = (response, uploadfile) => {
    imageUrl.value = 'api' + response.data
    addObject.value.imgUrl = response.data
    editObject.value.imgUrl = response.data
}
//上次新增数据
const addSave = async function () {
    addForm.value.validate(async (valid) => {
        if (valid) {
            //保存新增的数据 addObject
            //发送请求
            let result = await easyapi.postJson('/api/trainer', addObject.value);
            if (result.code == 200) {
                //当前页行数小于size则将数据添加到该页
                if (tableData.value.length < checkObj.value.size) {
                    tableData.value.push(result.data);
                } else {
                    checkData();
                }
                //刷新表单
                //提示新增成功
                ElMessage({
                    type: 'success',
                    message: '新增数据成功',
                })
                //关闭窗口
                closeAddWin()
            } else {
                ElMessage({
                    type: 'info',
                    message: result.message,
                })
            }
        } else {
            ElMessage({
                type: 'info',
                message: '格式错误',
            })
        }
    })
}

//修改数据
//显示编辑窗口
const openEditWin = function () {
    editWinVisible.value = true;
}
//关闭编辑窗口
const closeEditWin = function () {
    editWinVisible.value = false;
}
//点击编辑按钮，执行的方法
const edit = function (index, row) {
    //绑定要修改的数据
    editObject.value.trainerID = row.trainerID;
    imageUrl.value = 'api' + row.imgUrl
    editObject.value.imgUrl = row.imgUrl
    editObject.value.name = row.name;
    editObject.value.phoneNumber = row.phoneNumber;
    editObject.value.email = row.email;
    editObject.value.nationalIDNumber = row.nationalIDNumber;
    editObject.value.level = row.level;
    editObject.value.introduction = row.introduction
    editIndex = index;
    //打开对话框
    openEditWin();
}
//保存修改编辑数据
const editSave = async () => {

    editForm.value.validate(async (valid) => {
        if (valid) {
            //发送请求
            let result = await easyapi.putJson('/api/trainer', editObject.value)
            if (result.code == 200) {
                //刷新表单
                tableData.value[editIndex] = result.data;
                //提示
                ElMessage({
                    type: 'success',
                    message: '编辑数据成功',
                })
                //关闭窗口
                closeEditWin()
            } else {
                ElMessage({
                    type: 'info',
                    message: result.message,
                })
            }
        } else {
            ElMessage({
                type: 'info',
                message: '格式错误',
            })
        }
    })
}

//查询功能
const checkData = async (val) => {
    //获取当前页数
    if (typeof val == 'number') {
        checkObj.value.page = val;
    }
    //查询数据
    let result = await easyapi.getSearch('/api/trainer', checkObj.value)
    //更新表格中的数据
    tableData.value = result.data.list;
    console.log(result.data.list)
    total.value = result.data.count;
}


const getFullImageUrl = (relativeUrl) => {

    return `/api${relativeUrl}`;
}

//表单验证
const addForm = ref({})

const addCheckRules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    phoneNumber: [
        { required: true, message: '请输入电话号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的电子邮箱地址', trigger: ['blur', 'change'] }
    ],
    nationalIDNumber: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/, message: '请输入正确的身份证号', trigger: 'blur' }
    ],
    level: [
        { required: true, message: '请输入教练资质', trigger: 'blur' },
    ],
    introduction: [
        { required: true, message: '请输入教练介绍', trigger: 'blur' },
    ]
}

const editForm = ref({})

const editCheckRules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    phoneNumber: [
        { required: true, message: '请输入电话号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的电子邮箱地址', trigger: ['blur', 'change'] }
    ],
    nationalIDNumber: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/, message: '请输入正确的身份证号', trigger: 'blur' }
    ],
    level: [
        { required: true, message: '请输入资质', trigger: 'blur' },
    ],
    introduction: [
        { required: true, message: '请输入介绍', trigger: 'blur' },
    ]
}

</script>
<template>
    <el-input v-model="checkObj.name" style="width: 150px" placeholder="请输入查询的姓名" />
    <el-input v-model="checkObj.phoneNumber" style="width: 150px" placeholder="请输入查询的手机号" />
    <el-button type="primary" @click="checkData">查询</el-button>
    <el-button type="primary" @click="openAddWin">新增</el-button>
    <el-table :data="tableData" :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
        style="width: 100%">
        <el-table-column prop="imgUrl" label="头像" width="60px">
            <template v-slot="scope">
                <img :src="getFullImageUrl(scope.row.imgUrl)" style="width: 50px; height: 50px; object-fit: cover;">
            </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="level" label="资质" />
        <el-table-column prop="introduction" label="介绍" />
        <el-table-column prop="phoneNumber" label="电话号码" />
        <el-table-column prop="email" label="电子邮箱" width="200px" />
        <el-table-column prop="nationalIDNumber" label="身份证号" width="200px" />
        <el-table-column label="操作" width="180px" header-align="center">
            <template #default="scope">
                <el-button type="danger" @click="del(scope.$index, scope.row)">删除</el-button>
                <el-button type="success" @click="edit(scope.$index, scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页组件初始显示的页码 -->
    <!-- size:每页的条数 -->
    <el-pagination :page-size="checkObj.size" :current-page="checkObj.page" background layout="prev, pager, next"
        :total="total" @current-change="checkData" />


    <!--start 新增信息的弹出框 -->
    <el-dialog v-model="addWinVisible" title="新增教练数据" width="500">
        <el-form :model="addObject" :rules="addCheckRules" ref="addForm">
            <el-form-item label="头像" :label-width="80" prop="imgUrl">
                <el-upload class="avatar-uploader" action="api/img" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="姓名" :label-width="80" prop="name">
                <el-input v-model="addObject.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="资质" :label-width="80" prop="level">
                <el-input v-model="addObject.level" autocomplete="off" />
            </el-form-item>
            <el-form-item label="介绍" :label-width="80" prop="introduction">
                <el-input v-model="addObject.introduction" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话号码" :label-width="80" prop="phoneNumber">
                <el-input v-model="addObject.phoneNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电子邮箱" :label-width="80" prop="email">
                <el-input v-model="addObject.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="身份证号" :label-width="80" prop="nationalIDNumber">
                <el-input v-model="addObject.nationalIDNumber" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeAddWin">取消</el-button>
                <el-button type="primary" @click="addSave">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--end 新增信息的弹出框 -->

    <!--start 修改信息的弹出框 -->
    <el-dialog v-model="editWinVisible" title="修改教练数据" width="500">
        <el-form :model="editObject" :rules="editCheckRules" ref="editForm">
            <el-form-item label="头像" :label-width="80" prop="imgUrl">
                <el-upload class="avatar-uploader" action="api/img" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="姓名" :label-width="80" prop="name">
                <el-input v-model="editObject.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="资质" :label-width="80" prop="level">
                <el-input v-model="editObject.level" autocomplete="off" />
            </el-form-item>
            <el-form-item label="介绍" :label-width="80" prop="introduction">
                <el-input v-model="editObject.introduction" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话号码" :label-width="80" prop="phoneNumber">
                <el-input v-model="editObject.phoneNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电子邮箱" :label-width="80" prop="email">
                <el-input v-model="editObject.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="身份证号" :label-width="80" prop="nationalIDNumber">
                <el-input v-model="editObject.nationalIDNumber" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeEditWin">取消</el-button>
                <el-button type="primary" @click="editSave">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--end 修改信息的弹出框 -->

</template>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>